package main

import (
	"gitee.com/libbylg/pkgr/repo"
	"os"
	"os/exec"
	"path/filepath"
)

// pkgr ACTION ...
func CmdProxy(argv []string) int {
	if len(argv) < 2 {
		ERROR("Missing parameter, try -h for help")
		return 1
	}

	action := argv[1]

	if !repo.PathIsDir(repo.PKGREPO) {
		ERROR("The required environment variable $PKGREPO is missing")
		return 1
	}

	scriptFilepath := filepath.Join(repo.PKGREPO, ".pkgrepo", action, repo.INSTALL_SCRIPT_NAME)
	if !repo.PathIsFile(scriptFilepath) {
		ERROR("Unsupported command `%v'", action)
		return 1
	}

	// 找到 sh 进程
	sh, err := exec.LookPath("sh")
	if err != nil {
		ERROR("Unable to locate the application of `sh': %v", err.Error())
		return 1
	}

	// 构造命令行输入参数
	cmdArgs := make([]string, 0, len(argv))
	cmdArgs = append(cmdArgs, scriptFilepath)
	cmdArgs = append(cmdArgs, argv[1:]...)

	// sh script args...
	shcmd := exec.Command(sh, cmdArgs...)

	// 将命令的输出绑定到本进程的输出
	shcmd.Stdin = os.Stdin
	shcmd.Stdout = os.Stdout
	shcmd.Stderr = os.Stderr

	// 启动命令
	if err := shcmd.Run(); err != nil {
		ERROR("Execute action `%v' failed: %v", action, err.Error())
		return 1
	}

	// 检查脚本的返回值
	exitCode := shcmd.ProcessState.ExitCode()
	if exitCode != 0 {
		ERROR("Execute action `%v' failed(%v)", action, exitCode)
		return 1
	}

	return 0
}
